package com.gzwanchuang.lszg;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;

import android.content.res.TypedArray;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.gzwanchuang.lszg.base.BaseActivity;
import com.gzwanchuang.lszg.base.MainApplication;
import com.gzwanchuang.lszg.dialog.ActionDialog;
import com.gzwanchuang.lszg.module.main.HomeFragment;
import com.gzwanchuang.lszg.module.mine.MineFragment;
import com.gzwanchuang.lszg.net.Apis;
import com.gzwanchuang.lszg.net.NetworkManager;
import com.gzwanchuang.lszg.net.WebApis;
import com.gzwanchuang.lszg.net.interfaces.OnRequestCallBack;
import com.gzwanchuang.lszg.proto.Index;
import com.gzwanchuang.lszg.utils.APKVersionCodeUtils;
import com.gzwanchuang.lszg.utils.StatusBarUtil;
import com.gzwanchuang.lszg.view.NoScrollViewPager;
import com.gzwanchuang.lszg.web.ui.WebViewFragment;
import com.google.android.material.tabs.TabLayout;
import com.google.protobuf.InvalidProtocolBufferException;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import kale.ui.view.dialog.EasyDialog;

public class MainActivity extends BaseActivity {

    @BindView(R.id.viewPagers)
    NoScrollViewPager viewPager;
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;


    private long mExitTime;
    public String tureeName = "";
    private HomeFragment home;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StatusBarUtil.setRootViewFitsSystemWindows(this, false);
        StatusBarUtil.setTranslucentStatus(this);
        ButterKnife.bind(this);
        initMenus();
        initView();
        checkVersion();
        showAlert();
    }


    String[] tabNames;
    int[] tabIcons;

    private void initMenus() {
        tabNames = getResources().getStringArray(R.array.main_tabs);
        TypedArray ar = getResources().obtainTypedArray(R.array.main_tab_icons);
        int len = ar.length();
        tabIcons = new int[len];
        for (int i = 0; i < len; i++) {
            tabIcons[i] = ar.getResourceId(i, 0);
        }
        ar.recycle();
    }

    private void initView() {
        tureeName = getIntent().getStringExtra("trueName");
        List<Fragment> fragments = new ArrayList<>();
        fragments.add( home = new HomeFragment());
        fragments.add(WebViewFragment.newInstance(MainApplication.getServiceHost() + WebApis.statistics));
        fragments.add(WebViewFragment.newInstance(MainApplication.getServiceHost() + WebApis.qrcode));
//        fragments.add(new QrFragment());
//        fragments.add(WebViewFragment.newInstance(MainApplication.getServiceHost() + WebApis.businessSchool));
        fragments.add(new MineFragment());
        viewPager.setOffscreenPageLimit(4);
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public int getCount() {
                return fragments.size();
            }

            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return null;
            }

        });
        //设置图标
        tabLayout.setupWithViewPager(viewPager);
        for (int i = 0; i < tabNames.length; i++) {
            tabLayout.getTabAt(i).setCustomView(getTabView(tabNames[i], tabIcons[i]));
        }

        // 设置监听
        // 设置监听
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition()==0)
                {
                    home.onResume();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });


    }

    public View getTabView(String tabName, int tabIcon) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.tab_layout, null);
        ImageView iv_tab = view.findViewById(R.id.iv_tab);
        TextView tv_tab = view.findViewById(R.id.tv_tab);
        iv_tab.setImageResource(tabIcon);
        tv_tab.setText(tabName);
        return view;
    }

    //返回
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
                getSupportFragmentManager().popBackStack();
                return true;
            }
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Toast.makeText(mContext, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                MainApplication.finishAllActivity();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void checkVersion() {
        Index.get_app_version_info.Builder builder = Index.get_app_version_info.newBuilder();
        builder.setClient("android");
        NetworkManager.INSTANCE.post(Apis.versionCode, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) {
                new APKVersionCodeUtils().checkVerison(response, mContext);
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                hideProgress();
            }
        });

    }




    private void showAlert() {
        Index.get_agreement.Builder builder = Index.get_agreement.newBuilder();
        builder.setType("act_alert");
        NetworkManager.INSTANCE.post(Apis.get_agreement, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                Index.get_agreement agreement = Index.get_agreement.parseFrom(response);
                Log.e("mango", "onOk: " + agreement);
                if (agreement.getActState().equals("1")) {
                    ActionDialog.Builder builder = new ActionDialog.Builder(mContext);
                    builder.setContent(agreement.getContent());
                    EasyDialog build = builder.build();
                    build.show(getSupportFragmentManager());
                }
            }

            @Override
            public void onError(int errorCode, String errorMessage) {

            }
        });
    }
}
